<!-- V-webapp/src/views/CartView.vue -->
<template>
  <div class="cart-container">
    <!-- 顶部导航 -->
    <div class="page-header">
      <el-button @click="$router.back()" class="back-btn" type="primary" link>
        <el-icon><ArrowLeft /></el-icon>
      </el-button>
      <h2>购物车</h2>
      <el-button v-if="cartItems.length > 0" @click="clearCart" type="primary" link>
        清空
      </el-button>
    </div>

    <!-- 空购物车状态 -->
    <div v-if="cartItems.length === 0 && !loading" class="empty-cart">
      <el-empty description="购物车是空的">
        <el-button type="primary" @click="$router.push('/products')">
          去逛逛
        </el-button>
      </el-empty>
    </div>

    <!-- 加载状态 -->
    <div v-else-if="loading" class="loading-container">
      <el-skeleton :rows="3" animated />
    </div>

    <!-- 购物车列表 -->
    <div v-else class="cart-content">
      <div class="cart-list">
        <div 
          v-for="item in cartItems" 
          :key="item.id" 
          class="cart-item"
        >
          <el-checkbox 
            v-model="item.selected" 
            @change="updateSelection"
            class="item-checkbox"
          />
          
          <div class="item-image">
            <el-image 
              :src="getProductImage(item.product)" 
              fit="cover"
              class="image"
            >
              <template #error>
                <div class="image-error">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
          </div>
          
          <div class="item-info">
            <h3 class="item-name">{{ getProductName(item.product) }}</h3>
            <p class="item-desc">{{ getProductDescription(item.product) }}</p>
            <div class="item-price">¥{{ item.product.price }}</div>
            
            <div class="item-actions">
              <div class="quantity-control">
                <el-button 
                  :disabled="item.quantity <= 1"
                  @click="updateQuantity(item, item.quantity - 1)"
                  size="small"
                >
                  <el-icon><Minus /></el-icon>
                </el-button>
                <span class="quantity">{{ item.quantity }}</span>
                <el-button 
                  :disabled="item.quantity >= getProductStock(item.product)"
                  @click="updateQuantity(item, item.quantity + 1)"
                  size="small"
                >
                  <el-icon><Plus /></el-icon>
                </el-button>
              </div>
              
              <el-button 
                @click="removeItem(item.id)" 
                type="danger" 
                link
                class="delete-btn"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 结算栏 - 修复布局 -->
      <div v-if="cartItems.length > 0" class="checkout-bar-wrapper">
        <div class="checkout-bar">
          <div class="checkout-left">
            <el-checkbox 
              v-model="selectAll" 
              @change="handleSelectAll"
            >
              全选
            </el-checkbox>
          </div>
          
          <div class="checkout-right">
            <div class="total-info">
              <div class="total-amount">
                合计: <span class="amount">¥{{ totalAmount }}</span>
              </div>
              <div class="total-count">已选 {{ selectedCount }} 件商品</div>
            </div>
            
            <el-button 
              type="primary" 
              class="checkout-btn"
              :disabled="selectedCount === 0"
              @click="handleCheckout"
            >
              结算({{ selectedCount }})
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  ArrowLeft, 
  Picture, 
  Plus, 
  Minus, 
  Delete 
} from '@element-plus/icons-vue'
import { 
  getCart, 
  updateCartItem, 
  removeCartItem, 
  clearCart as clearCartAPI 
} from '@/api/cart'
import type { CartItem } from '@/api/cart'

// 导入本地商品图片
import julyDream from '@/assets/images/七月梦境.jpg'
import julyBadge from '@/assets/images/七月吧唧.jpg'
import mousePad from '@/assets/images/鼠标垫.jpg'
import zhaotaiyang from '@/assets/images/赵太阳立牌.jpg'
import defaultProductImg from '@/assets/images/S2.jpg'

const router = useRouter()
const cartItems = ref<CartItem[]>([])
const selectAll = ref(false)
const loading = ref(false)

// 图片映射表
const imageMap: Record<string, any> = {
  '七月梦境.jpg': julyDream,
  '七月吧唧.jpg': julyBadge,
  '鼠标垫.jpg': mousePad,
  '赵太阳立牌.jpg': zhaotaiyang,
  'S2.jpg': defaultProductImg
}

// 获取购物车列表 - 完全重写
const fetchCart = async () => {
  loading.value = true
  try {
    console.log('🛒 开始获取购物车数据...')
    
    // 检查登录状态
    const token = localStorage.getItem('token')
    if (!token) {
      console.log('❌ 用户未登录')
      cartItems.value = []
      ElMessage.warning('请先登录')
      return
    }

    console.log('🔑 Token存在，发送请求...')
    const response = await getCart()
    console.log('✅ 购物车API完整响应:', response)
    
    // 详细检查响应结构
    if (response && (response.success || response.code === 200)) {
      const cartData = response.data || {}
      const items = cartData.items || []
      
      console.log('📦 解析到的购物车项:', items)
      
      if (items.length > 0) {
        cartItems.value = items.map((item: any) => {
          console.log('🔍 处理购物车项详情:', item)
          return {
            id: item.cart_id || item.id,
            cart_id: item.cart_id,
            product_id: item.product_id,
            quantity: item.quantity,
            selected: false,
            product: {
              id: item.product?.product_id || item.product?.id || 0,
              product_id: item.product?.product_id,
              name: item.product?.product_name || item.product?.name || '未知商品',
              product_name: item.product?.product_name,
              description: item.product?.product_description || item.product?.description || '暂无描述',
              price: item.product?.price || 0,
              stock: item.product?.stock_quantity || item.product?.stock || 0,
              stock_quantity: item.product?.stock_quantity,
              cover_image: item.product?.cover_image,
              product_images: item.product?.product_images || [],
              anchor: item.product?.anchor
            }
          }
        })
        console.log('✅ 成功加载真实购物车数据:', cartItems.value.length, '件商品')
        
        // 关键修复：保存购物车数据到本地存储
        localStorage.setItem('cartData', JSON.stringify(cartItems.value))
        console.log('💾 购物车数据已保存到本地存储')
        
      } else {
        cartItems.value = []
        console.log('🛒 购物车为空（真实数据）')
      }
    } else {
      console.warn('⚠️ 购物车API响应格式异常，使用模拟数据')
      throw new Error('API响应格式异常')
    }
  } catch (error: any) {
    console.error('❌ 获取购物车失败:', error)
    
    // 详细错误信息
    if (error.response) {
      console.error('❌ 服务器响应错误:', {
        status: error.response.status,
        statusText: error.response.statusText,
        data: error.response.data
      })
      
      if (error.response.status === 401) {
        ElMessage.error('登录已过期，请重新登录')
        localStorage.removeItem('token')
        router.push('/login')
        return
      } else if (error.response.status === 404) {
        ElMessage.error('购物车接口不存在，请检查后端服务')
      } else {
        ElMessage.error(`服务器错误: ${error.response.status}`)
      }
    } else if (error.request) {
      console.error('❌ 网络请求失败:', error.request)
      ElMessage.error('网络连接失败，请检查后端服务是否启动')
    } else {
      console.error('❌ 其他错误:', error.message)
      ElMessage.error('获取购物车失败: ' + error.message)
    }
    
    // 只在开发环境使用模拟数据
    if (import.meta.env.MODE === 'development') {
      console.log('🛠️ 开发环境：使用模拟数据')
      cartItems.value = generateMockCartItems()
      ElMessage.info('使用模拟数据展示')
    } else {
      cartItems.value = []
    }
  } finally {
    loading.value = false
  }
}

// 生成模拟购物车数据
const generateMockCartItems = () => {
  return [
    {
      id: 1,
      product_id: 1,
      quantity: 2,
      selected: false,
      product: {
        id: 1,
        name: '测试商品1',
        description: '这是一个测试商品描述',
        price: 99.99,
        stock: 10,
        cover_image: 'S2.jpg'
      }
    },
    {
      id: 2,
      product_id: 2,
      quantity: 1,
      selected: false,
      product: {
        id: 2,
        name: '测试商品2',
        description: '这是另一个测试商品描述',
        price: 199.99,
        stock: 5,
        cover_image: 'S2.jpg'
      }
    }
  ]
}

// 获取商品图片
const getProductImage = (product: CartItem['product']) => {
  // 优先使用 cover_image 映射到本地图片
  if (product.cover_image && imageMap[product.cover_image]) {
    return imageMap[product.cover_image]
  }
  // 其次使用 product_images
  if (product.product_images && product.product_images.length > 0) {
    return product.product_images[0].image_url
  }
  // 最后使用默认图片
  return defaultProductImg
}

// 获取商品名称（兼容不同字段名）
const getProductName = (product: CartItem['product']) => {
  return product.name || product.product_name || '未知商品'
}

// 获取商品描述（兼容不同字段名）
const getProductDescription = (product: CartItem['product']) => {
  return product.description || '暂无描述'
}

// 获取商品库存（兼容不同字段名）
const getProductStock = (product: CartItem['product']) => {
  return product.stock || product.stock_quantity || 0
}

// 更新商品数量
const updateQuantity = async (item: CartItem, newQuantity: number) => {
  if (newQuantity < 1 || newQuantity > getProductStock(item.product)) return
  
  try {
    console.log('🛒 更新购物车数量:', item.id, newQuantity)
    await updateCartItem(item.id, { quantity: newQuantity })
    item.quantity = newQuantity
    ElMessage.success('更新成功')
    
    // 关键修复：更新本地存储
    localStorage.setItem('cartData', JSON.stringify(cartItems.value))
  } catch (error: any) {
    console.error('❌ 更新购物车失败:', error)
    ElMessage.error(error.response?.data?.message || '更新失败')
  }
}

// 移除商品
const removeItem = async (itemId: number) => {
  try {
    await ElMessageBox.confirm('确定要移除这个商品吗？', '提示', {
      type: 'warning'
    })
    
    console.log('🛒 删除购物车商品:', itemId)
    await removeCartItem(itemId)
    ElMessage.success('移除成功')
    await fetchCart() // 重新获取购物车数据
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('❌ 删除购物车失败:', error)
      ElMessage.error('移除失败')
    }
  }
}

// 清空购物车
const clearCart = async () => {
  try {
    await ElMessageBox.confirm('确定要清空购物车吗？', '提示', {
      type: 'warning'
    })
    
    console.log('🛒 清空购物车')
    await clearCartAPI()
    ElMessage.success('清空成功')
    await fetchCart() // 重新获取购物车数据
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('❌ 清空购物车失败:', error)
      ElMessage.error('清空失败')
    }
  }
}

// 更新选择状态
const updateSelection = () => {
  selectAll.value = cartItems.value.length > 0 && cartItems.value.every(item => item.selected)
}

// 处理全选
const handleSelectAll = (value: boolean) => {
  cartItems.value.forEach(item => {
    item.selected = value
  })
}

// 计算总金额
const totalAmount = computed(() => {
  return cartItems.value
    .filter(item => item.selected)
    .reduce((total, item) => total + item.product.price * item.quantity, 0)
    .toFixed(2)
})

// 计算选中数量
const selectedCount = computed(() => {
  return cartItems.value.filter(item => item.selected).length
})

// 处理结算 - 关键修复：保存选中商品数据
const handleCheckout = () => {
  const selectedItems = cartItems.value.filter(item => item.selected)
  if (selectedItems.length === 0) {
    ElMessage.warning('请选择要结算的商品')
    return
  }
  
  console.log('🛒 结算商品:', selectedItems)
  
  // 关键修复：保存选中的商品到本地存储
  localStorage.setItem('checkoutItems', JSON.stringify(selectedItems))
  console.log('💾 选中的商品已保存到本地存储')
  
  // 跳转到订单确认页面
  router.push({
    path: '/checkout',
    query: {
      items: selectedItems.map(item => item.id).join(',')
    }
  })
}

onMounted(() => {
  fetchCart()
})
</script>

<style scoped>
.cart-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 16px;
  padding-bottom: 120px; /* 为底部结算栏留出足够空间 */
  box-sizing: border-box;
  max-width: 100%;
  overflow-x: hidden;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  color: white;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

.empty-cart {
  padding-top: 100px;
}

.loading-container {
  padding: 20px 0;
}

.cart-content {
  display: flex;
  flex-direction: column;
  min-height: calc(100vh - 120px);
}

.cart-list {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 90px; /* 为结算栏留出足够空间 */
}

.cart-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  background: white;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.item-checkbox {
  margin-top: 8px;
}

.item-image {
  width: 80px;
  height: 80px;
  flex-shrink: 0;
}

.item-image .image {
  width: 100%;
  height: 100%;
  border-radius: 8px;
}

.image-error {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  border-radius: 8px;
  color: #999;
}

.item-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.item-name {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  line-height: 1.4;
}

.item-desc {
  margin: 0;
  font-size: 14px;
  color: #666;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.item-price {
  font-size: 18px;
  font-weight: 700;
  color: #ff4757;
}

.item-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.quantity-control {
  display: flex;
  align-items: center;
  gap: 8px;
}

.quantity {
  padding: 0 12px;
  font-size: 14px;
  font-weight: 600;
}

.delete-btn {
  color: #ff4757;
}

/* 完全重写结算栏布局 - 修复宽度问题 */
.checkout-bar-wrapper {
  position: fixed;
  bottom: 70px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 1000;
  width: 100%;
  max-width: 480px; /* 限制最大宽度与手机页面一致 */
  padding: 0 16px;
  box-sizing: border-box;
}

.checkout-bar {
  background: white;
  padding: 12px 20px;
  display: flex;
  justify-content: space-between; /* 改为左右分布 */
  align-items: center;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  border-radius: 12px;
  width: 100%;
  max-width: 100%;
  box-sizing: border-box;
  gap: 0; /* 移除元素间距，使用左右分布 */
}

.checkout-left {
  display: flex;
  align-items: center;
  flex-shrink: 0;
}

.checkout-right {
  display: flex;
  align-items: center;
  gap: 20px;
  flex-shrink: 0;
}

.total-info {
  text-align: right; /* 金额信息右对齐 */
  flex-shrink: 0;
}

.total-amount {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  white-space: nowrap;
}

.amount {
  color: #ff4757;
  font-size: 18px;
}

.total-count {
  font-size: 12px;
  color: #999;
  white-space: nowrap;
}

.checkout-btn {
  padding: 10px 24px;
  border-radius: 20px;
  font-weight: 600;
  white-space: nowrap;
  flex-shrink: 0;
  font-size: 14px;
  min-width: 100px;
}

/* 响应式设计 */
@media (max-width: 375px) {
   .checkout-bar {
    padding: 10px 16px;
  }
  
  
  .checkout-right {
    gap: 15px;
  }
    .checkout-btn {
    padding: 8px 16px;
    font-size: 13px;
    min-width: 80px;
  }
  .total-info {
    min-width: 80px;
  }
  
  .total-amount {
    font-size: 13px;
  }
  
  .amount {
    font-size: 14px;
  }
  
  .total-count {
    font-size: 11px;
  }
}
</style>